package com.kedou.sdk.utils;

import android.Manifest;
import android.app.ActivityManager;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SharedPreferences;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.text.format.Formatter;
import android.util.Log;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import java.util.UUID;

public final class AndroidDeviceGenerator {

    private static final String READ_PHONE_STATE = Manifest.permission.READ_PHONE_STATE;

    private static final String DEVICE_UUID_FILE = "device_uuid_info";
    private static final String DEVICE_UUID_KEY = "uuid";

    public static final String UNKNOWN = "unknown";


    private AndroidDeviceGenerator() {

    }
    protected static String uuid;

    /**
     * 获取安卓设备型号
     *
     * @return 返回安卓设备型号
     */
    public static String getAndroidDeviceModel() {
        return Build.BRAND+":"+Build.MODEL+":"+Build.DEVICE;
    }


    /**
     * 获取手机内存大小
     *
     * @param context 上下文
     * @return
     */
    public static String getTotalMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.totalMem);
    }

    public static String getIMEI(Context context){
        String imei = "";
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
            if(Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
                imei = tm.getDeviceId();
            }else {
                Method method = tm.getClass().getMethod("getImei");
                imei = (String) method.invoke(tm);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return imei;
    }


    /**
     * 获取当前可用内存大小s
     *
     * @param context
     * @return
     */
    public static String getAvailMemory(Context context) {
        ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ActivityManager.MemoryInfo mi = new ActivityManager.MemoryInfo();
        am.getMemoryInfo(mi);
        return Formatter.formatFileSize(context, mi.availMem);
    }



    public static String getDeviceID(Context context) {
        if (uuid == null) {
            generateDeviceID(context);
        }
        return uuid;
    }

    public static void generateDeviceID(Context context) {

        if (uuid == null) {
            synchronized (AndroidDeviceGenerator.class) {
                if (uuid == null) {
                    final SharedPreferences prefs = context.getSharedPreferences("g_device_id.xml", 0);
                    final String id = prefs.getString("device_id", null);

                    if (id != null) {
                        // Use the ids previously computed and stored in the prefs file
                        uuid = id;
                    } else {
                        final String androidId = Settings.Secure.getString(context.getContentResolver(), Settings.Secure.ANDROID_ID);
                        Log.e("51wan","androidId"+androidId);
                        // Use the Android ID unless it's broken, in which case fallback on deviceId,
                        // unless it's not available, then fallback on a random number which we store
                        // to a prefs file
                        try {
                            if (!TextUtils.isEmpty(androidId)&&!"9774d56d682e549c".equals(androidId)) {
                                uuid = UUID.nameUUIDFromBytes(androidId.getBytes("utf8")).toString();
                                Log.e("51wan","nameUUIDFromBytes");
                            } else {
                                Log.e("51wan","randomUUID");
                                uuid = UUID.randomUUID().toString();
                            }
                        } catch (UnsupportedEncodingException e) {
                            throw new RuntimeException(e);
                        }

                        // Write the value out to the prefs file
                        prefs.edit().putString("device_id", uuid.toString()).commit();

                    }
                }
            }
        }
    }

    public static String getMacAddress(Context context) {

        final SharedPreferences prefs = context.getSharedPreferences("g_device_id.xml", 0);
        final String id = prefs.getString("device_mac", null);
        Log.e("51wan","id"+id);
        if(!TextUtils.isEmpty(id)) return id;
        String mac = getMac1(context);
        Log.e("51wan","getMac1"+mac);
        if (!TextUtils.isEmpty(mac)&&!"02:00:00:00:00:00".equals(mac)) {
            prefs.edit().putString("device_mac",mac).commit();
            return mac;
        }
        mac = getMac2();
        Log.e("51wan","getMac1"+mac);
        if (!TextUtils.isEmpty(mac)&&!"02:00:00:00:00:00".equals(mac)) {
            prefs.edit().putString("device_mac",mac).commit();
            return mac;
        }
        mac = getMac3();
        Log.e("51wan","getMac1"+mac);
        if (!TextUtils.isEmpty(mac)&&!"02:00:00:00:00:00".equals(mac)) {
            prefs.edit().putString("device_mac",mac).commit();
            return mac;
        }
        mac = getMac4();
        Log.e("51wan","getMac1"+mac);
        if (!TextUtils.isEmpty(mac)&&!"02:00:00:00:00:00".equals(mac)) {
            prefs.edit().putString("device_mac",mac).commit();
            return mac;
        }
        return "02:00:00:00:00:00";
    }


    private static String getMac1(Context ctx) {
        WifiManager wifi = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE);
        WifiInfo info = wifi.getConnectionInfo();
        if (info != null) {
            return "02:00:00:00:00:00".equals(info.getMacAddress())?"":info.getMacAddress();
        }
        return null;
    }
    private static String getMac5(Context ctx) {
        String macAddress="";
        try {
            ContentResolver contentResolver = ctx.getContentResolver();
             macAddress = Settings.Secure.getString(contentResolver, "bluetooth_address");
            // 处理获取到的MAC地址
        } catch (Exception e) {
            e.printStackTrace();
        }
        return  macAddress;
    }

    public static String getMac2() {
        String macSerial = null;
        String str = "";
        try {
            Process pp = Runtime.getRuntime().exec("cat /sys/class/net/wlan0/address ");
            InputStreamReader ir = new InputStreamReader(pp.getInputStream());
            LineNumberReader input = new LineNumberReader(ir);
            for (; null != str;) {
                str = input.readLine();
                if (str != null) {
                    macSerial = str.trim();// 去空格
                    break;
                }
            }
        } catch (IOException ex) {
            // 赋予默认值
            ex.printStackTrace();
        }
        return "02:00:00:00:00:00".equals(macSerial)?"":macSerial;
    }

    /**
     * 根据IP地址获取MAC地址
     *
     * @return
     */
    public static String getMac3() {
        String strMacAddr = null;
        try {
            // 获得IpD地址
            InetAddress ip = getLocalInetAddress();
            byte[] b = NetworkInterface.getByInetAddress(ip).getHardwareAddress();
            StringBuffer buffer = new StringBuffer();
            for (int i = 0; i < b.length; i++) {
                if (i != 0) {
                    buffer.append(':');
                }
                String str = Integer.toHexString(b[i] & 0xFF);
                buffer.append(str.length() == 1 ? 0 + str : str);
            }
            strMacAddr = buffer.toString().toUpperCase();
        } catch (Exception e) {

        }

        return "02:00:00:00:00:00".equals(strMacAddr)?"":strMacAddr;
    }

    /**
     * 获取移动设备本地IP
     *
     * @return
     */
    private static InetAddress getLocalInetAddress() {
        InetAddress ip = null;
        try {
            // 列举
            Enumeration<NetworkInterface> en_netInterface = NetworkInterface.getNetworkInterfaces();
            while (en_netInterface.hasMoreElements()) {// 是否还有元素
                NetworkInterface ni = (NetworkInterface) en_netInterface.nextElement();// 得到下一个元素
                Enumeration<InetAddress> en_ip = ni.getInetAddresses();// 得到一个ip地址的列举
                while (en_ip.hasMoreElements()) {
                    ip = en_ip.nextElement();
                    if (!ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1)
                        break;
                    else
                        ip = null;
                }

                if (ip != null) {
                    break;
                }
            }
        } catch (SocketException e) {

            e.printStackTrace();
        }
        return ip;
    }

    /**
     * 通过网络接口取
     *
     * @return
     */
    public static String getMac4() {
        try {
            List<NetworkInterface> all = Collections.list(NetworkInterface.getNetworkInterfaces());
            for (NetworkInterface nif : all) {
                if (!nif.getName().equalsIgnoreCase("wlan0"))
                    continue;

                byte[] macBytes = nif.getHardwareAddress();
                if (macBytes == null) {
                    return null;
                }

                StringBuilder res1 = new StringBuilder();
                for (byte b : macBytes) {
                    res1.append(String.format("%02X:", b));
                }

                if (res1.length() > 0) {
                    res1.deleteCharAt(res1.length() - 1);
                }
                return res1.toString();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
}


